/* eslint-disable max-len */
const { Service } = require('egg')
const cheerio = require('cheerio')
const { tableToList } = require('../utils/tools')

const gradeStatus = (str) => {
  if (/^\d+$/.test(str)) {
    return [str, (Number(str) >= 60) ? '已获' : '已开未获']
  }
  return [str, str === '不及格' ? '已开未获' : '已获']
}

module.exports = class CreditService extends Service {
  /**
   * * 学分修读情况
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = 'https://webvpn.hnust.edu.cn/https/77726476706e69737468656265737421fbf34b8b693866456d1cc7a99c406d3642/jsxsd/xxwcqk/xxwcqk_idxOntx.do' // 学习情况（体系）get
    const scheduletUrl = `${this.ctx.state.baseUrl}/jsxsd/xxwcqk/xxwcqkOnkctx.do` // 学习情况（体系）post
    const gradeUrl = `${this.ctx.state.baseUrl}/jsxsd/kscj/cjcx_list` // 成绩
    const planUrl = `${this.ctx.state.baseUrl}/jsxsd/pyfa/topyfamx` // 培养方案
    const P1 = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        Host: 'webvpn.hnust.edu.cn',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const $ = cheerio.load(P1.data.toString())
    const bdzydm = $('input[name="ndzydm"]').attr('value')
    const P2 = await this.ctx.curl(scheduletUrl, {
      method: 'POST',
      data: {
        ndzydm: bdzydm,
        jx0301zxjhid: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const P3 = await this.ctx.curl(gradeUrl, {
      method: 'POST',
      data: {
        kksj: '',
        kcxz: '',
        kcmc: '',
        xsfs: 'all',
      },
      headers: {
        Cookie,
        Host: 'webvpn.hnust.edu.cn',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
    })
    const P4 = await this.ctx.curl(planUrl, {
      method: 'GET',
      headers: {
        Cookie,
        Host: 'webvpn.hnust.edu.cn',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    // console.log('P4', P4.data.toString());
    const [R1, R2, R3, R4] = await Promise.all([P1, P2, P3, P4])
    if (R1.status === 200 && R2.status === 200 && R3.status === 200 && R4.status === 200) {
      try {
        /**
         * 获取选修课程应修分数
         */
        const needTable = tableToList(P2.data.toString(), '.layui-table')
        const need = { } // 课程类别-应修学分
        for (let i = 1; i < needTable.length - 2; i++) {
          need[needTable[i][0]] = needTable[i][1]
        }
        console.log('need', need)
        /* end */

        /* 从成绩页面获取修读情况 */
        const temD = {}
        const gradeTable = tableToList(R3.data.toString(), '#dataList')
        const saveName = []
        gradeTable.forEach((item, idx) => {
          if (idx === 0 || !item[7]) return true // 去掉课程性质为空课程
          const [grade, status] = gradeStatus(item[5])

          if (saveName.includes(item[3])) { // 重复课程取最高分
            if (status === '已获') {
              temD[item[3]][0] = item[1]
              temD[item[3]][1] = grade
              temD[item[3]][4] = status
            }
            return true
          }

          temD[item[3]] = [item[1], item[5], item[4], `${item[7]}程(${item[10]})`, status]
          saveName.push(item[3])
          return true
        })

        /* end */
        /*
          1. 从培养计划中获取课程名称及课程性质，用户得到修读中课程的课程性质
          2. 统计非选修课程需要修读的学分
        */
        const nameType = {}
        let type = ''
        const tableList2 = tableToList(R4.data.toString(), '#mxh')
        tableList2.forEach((item, idx) => {
          if (idx < 2) return true
          if (item[0] === '合计') return false
          if (item[0] === '小计') {
            if (!type.includes('专业') || !type.includes('选修')) { need[type] = item[5] }
            type = ''
            return true
          }
          if (type === '') type = item[0].replace(/\(.*?\)/g, '') // 处理后的类型名称
          nameType[item[3]] = type
          return true
        })
        console.log('nameType', nameType)
        /* end */

        /* 数据准备完成，开始构造最终数据 */
        const saveType = [] // 课程性质
        const result = []
        for (const key in temD) {
          const type_ = temD[key][3]
          const index = saveType.indexOf(type_)
          if (index === -1) {
            saveType.push(type_)
            result.push({
              category: type_,
              details: [{
                N: key,
                T: temD[key][0],
                G: temD[key][1],
                C: temD[key][2],
                S: temD[key][4],
              }],
              need: need[type_],
              has: temD[key][4] === '已获' ? temD[key][2] : '0',
            })
          } else {
            result[index].details.push({
              N: key,
              T: temD[key][0],
              G: temD[key][1],
              C: temD[key][2],
              S: temD[key][4],
            })
            if (temD[key][4] === '已获') result[index].has = `${Number(temD[key][2]) + Number(result[index].has)}`
          }
        }
        return result
      } catch (err) {
        return err
      }
    }
    return ''
  }

  /**
   * * 创新学分、素拓分、第二课堂分
   * @return {Array} *
   */
  async extra() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/pyfa/cxxf_query`
    console.log('apiUrl', apiUrl)
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })

    const header = ['学期', '项目名称', '学分', '编号', '类型', '备注'] // 列名称
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        /* [ '序号', '学年学期', '项目编号', '学号', '姓名', '学分', '学分类型', '备注' ]; */
        const columnNeed = [1, 3, 6, 2, 7, 8] // 需要提取的列序号
        if (tableList.length === 0 || tableList[1][0] === '未查询到数据') return { table: [], header, has: '0' }

        const table = []
        let has = 0
        for (let i = 1; i < tableList.length; i++) {
          const tem = []
          columnNeed.forEach((idx) => { tem.push(tableList[i][idx]) })
          if (tem[0]) { table.push(tem) }
          has += Number(tem[2])
        }
        console.log(tableList)
        return { table, header, has: `${has}` }
      } catch (err) {
        return err
      }
    }
    return { table: [], header, has: '0' }
  }
}
